<?php

namespace Framework;

$routes = require basePath('routes.php');


// if (array_key_exists($uri, $routes)) {
//     require(basePath($routes[$uri]));
//   } else {
//     http_response_code(404);
//     require(basePath($routes['404']));
//   }
  
class Router{
  protected $routes =[];


  private function registerRoute($method,$uri,$action){

      list($controller,$controllerMethod) = explode('@',$action);
    
    $this->routes[]=[
      'method'=>$method,
      'uri'=>$uri,
      'controller' => $controller,
      'controllerMethod' => $controllerMethod
    ];
  }


  public function error($httpCode = 404)
{
    http_response_code($httpCode);
    loadView("error/{$httpCode}");
    exit;
}
  /**
   * 添加一个 GET 路由
   * 
   * @parm string $uri
   * @parm string $controller
   * @return void
   */
  public function addGet($uri,$controller){
    $this->registerRoute('GET',$uri,$controller);
  }

    /**
   * 添加一个 POST 路由
   * 
   * @parm string $uri
   * @parm string $controller
   * @return void
   */
  public function addPost($uri,$controller){
    $this->registerRoute('POST',$uri,$controller);
  }
    /**
   * 添加一个 PUT 路由
   * 
   * @parm string $uri
   * @parm string $controller
   * @return void
   */
  public function addPut($uri,$controller){
    $this->registerRoute('PUT',$uri,$controller);
  }

    /**
   * 添加一个 DELETE 路由
   * 
   * @parm string $uri
   * @parm string $controller
   * @return void
   */
  public function addDelete($uri,$controller){
    $this->registerRoute('DELETE',$uri,$controller);
  }

  public function route($uri,$method){
    foreach($this->routes as $route){
      if($route['uri']===$uri && $route['method']===$method)
      {
        //获得控制器和控制器方法
        $controller = 'App\\Controllers\\' . $route['controller'];
        $controllerMethod=$route['controllerMethod'];
        
        //实例化控制器和调用方法
        $controllerInstance = new $controller();
        $controllerInstance->$controllerMethod();
      }
    }
    $this->error();  
  }
}
